<?php

namespace App\Http\Middleware;

use Silber\Bouncer\Bouncer;

use Closure;

class ScopeBouncer
{
    /**
     * The Bouncer instance.
     *
     * @var \Silber\Bouncer\Bouncer
     */
    protected $bouncer;

    /**
     * Constructor.
     *
     * @param \Silber\Bouncer\Bouncer  $bouncer
     */
    public function __construct(Bouncer $bouncer)
    {
        $this->bouncer = $bouncer;
    }

    /**
     * Set the proper Bouncer scope for the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Here you may use whatever mechanism you use in your app
        // to determine the current tenant. To demonstrate, the
        // $tenantId is set here from the user's account_id.
//        if(!($user = auth('api')->user())){
//            $user = $request->user();
//        }
        $user = auth()->user();
        
//        $tenantId = null;
//        if($user && !$user->isSuper()){
//            if($user->Co_ID==null) {
//                return response()->json(['msg' => '该用户没有分配公司, 请联系管理员'], 422);
//            }
//            $tenantId = $user->Co_ID;
//        }
       //$tenantId = $user->userid;
         
       $tenantId = $user->Co_ID;
         
        $request->merge(['sysParams'=>[ 'company_id'=>$user->Co_ID, 'site_id'=>$user->site_id, ]]);
      //  $tenantId =2;
       // $this->bouncer->scope()->dontScopeRoleAbilities();
       // $this->bouncer->scope()->onlyRelations();
      $this->bouncer->scope()->to($tenantId);

        return $next($request);
    }
}
